package com.kexio.dynamic.datasource.config;

import com.kexio.dynamic.datasource.aspect.DataSourceAspect;
import com.kexio.dynamic.datasource.service.DataSourceSwitchService;
import com.kexio.dynamic.datasource.service.DynamicDataSourceService;
import com.kexio.dynamic.datasource.service.TenantDataSourceRouter;
import com.kexio.dynamic.datasource.service.impl.DefaultDataSourceSwitchService;
import com.kexio.dynamic.datasource.service.impl.DefaultDynamicDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import jakarta.annotation.PostConstruct;

/**
 * 动态数据源配置类
 * 
 * 功能说明：
 * - 配置动态数据源管理服务
 * - 配置数据源切换服务
 * - 配置租户数据源路由
 * - 启用AOP支持
 * 
 * @author Kexio
 * @since 1.0.0
 */
@Configuration
@EnableAspectJAutoProxy
@ConditionalOnProperty(name = "kexio.dynamic.datasource.enabled", havingValue = "true", matchIfMissing = true)
public class DynamicDataSourceConfig {

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceConfig.class);

    @PostConstruct
    public void init() {
        log.info("==> Kexio动态数据源模块已启用");
        log.debug("动态数据源模块包含: 多数据源管理、租户路由、AOP切换");
    }

    /**
     * 动态数据源管理服务
     */
    @Bean
    @ConditionalOnMissingBean
    public DynamicDataSourceService dynamicDataSourceService() {
        log.debug("==> 创建DynamicDataSourceService实例");
        return new DefaultDynamicDataSourceService();
    }

    /**
     * 数据源切换服务
     */
    @Bean
    @ConditionalOnMissingBean
    public DataSourceSwitchService dataSourceSwitchService(DynamicDataSourceService dynamicDataSourceService) {
        log.debug("==> 创建DataSourceSwitchService实例");
        return new DefaultDataSourceSwitchService(dynamicDataSourceService);
    }

    /**
     * 租户数据源路由器
     */
    @Bean
    @ConditionalOnMissingBean
    public TenantDataSourceRouter tenantDataSourceRouter() {
        log.debug("==> 创建TenantDataSourceRouter实例");
        return new TenantDataSourceRouter();
    }

    /**
     * 数据源切换AOP切面
     */
    @Bean
    @ConditionalOnMissingBean
    public DataSourceAspect dataSourceAspect(DataSourceSwitchService dataSourceSwitchService,
                                            TenantDataSourceRouter tenantDataSourceRouter) {
        log.debug("==> 创建DataSourceAspect实例");
        return new DataSourceAspect(dataSourceSwitchService, tenantDataSourceRouter);
    }
}
